"""
 -*- coding: utf-8-*-
 @File: jenkins_demo01.py
 @Author: chen
 @time: 2023/11/25/ 13:02
"""
import jenkinsapi


class JenkinsApiDemo:
    host = "http://192.168.111.100:5003"
    username = "admin100"
    password = "1121f1466861fbb826ae47a520ecb91f55"

    def __init__(self):
        self.jenkins = jenkinsapi.jenkins.Jenkins(self.host, self.username, self.password)

    def get_all_jobs(self):
        jobs = self.jenkins.keys()
        print(jobs)
        job_info = self.jenkins.get_jobs_info()
        job_list = []
        for i in job_info:
            job_list.append(i[0])
        print(job_info)
        print(job_list)

    def get_job_info(self, job_name):
        # 获取job对象
        my_job = self.jenkins.get_job(job_name)
        print(my_job.get_config())
        # 获取最后一次构建对象
        print(my_job.get_last_build())
        # 获取最后一次完成的构建对象
        print(my_job.get_last_completed_build())
        # 获取最后一次成功的构建对象
        print(my_job.get_last_good_build())
        # 获取最后一次失败的构建编号
        print(my_job.get_last_failed_buildnumber())
        # self.jenkins.python_api_url()
        # print()

    def deal_job(self, job_name):
        my_job = self.jenkins.get_job(job_name)
        with open(f"{job_name}_config.xml", "w", encoding="utf-8") as f_obj:
            config = my_job.get_config()
            f_obj.write(config)

    def create_job(self, new_job):
        with open("./python_api_test_config.xml", "r", encoding="UTF-8") as f:
            config = f.read().encode("utf-8")
            print(config)
        self.jenkins.create_job(new_job, config)

    def get_job_built_info(self, job_name):
        my_job = self.jenkins.get_job(job_name)
        built_info = my_job.get_build(buildnumber=10)
        # 获取构建对象的时间戳
        # print(built_info.get_timestamp())
        # 获取控制台日志
        # print(built_info.get_console())
        # 获取构建参数
        print(built_info.get_params())
        # 获取构建的状态
        print(built_info.get_status())
        # 获取构建的变更日志
        print(built_info.get_changeset_items())
        # 删除指定构建
        # my_job.delete_build(1)


if __name__ == '__main__':
    jk0 = JenkinsApiDemo()
    # jk0.get_all_jobs()
    # jk0.get_job_info("python_api_test")
    # jk0.create_job("new_job01")
    jk0.get_job_built_info("python_api_test")
